﻿using System.Collections.Generic;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;

namespace block_explorer.Util
{
    class DebugTextureTiler : DrawableGameComponent
    {
        private SpriteBatch mSpriteBatch;
        private IList<Texture2D> mTextures;
        private int mTileWidth;
        private int mTileHeight;
        private Rectangle mViewRect;

        public DebugTextureTiler(Game game, int tileWidth, int tileHeight, Rectangle viewRect)
            : base(game)
        {
            mTextures = new List<Texture2D>();
            mTileWidth = tileWidth;
            mTileHeight = tileHeight;
            mViewRect = viewRect;
        }

        public override void Initialize()
        {
            base.Initialize();
        }

        protected override void LoadContent()
        {
            mSpriteBatch = new SpriteBatch(GraphicsDevice);

            base.LoadContent();
        }

        public void AddTexture(Texture2D texture)
        {
            mTextures.Add(texture);
        }

        public override void Draw(GameTime gameTime)
        {
            mSpriteBatch.Begin(SpriteSortMode.BackToFront, BlendState.Opaque, SamplerState.PointWrap, DepthStencilState.Default, RasterizerState.CullCounterClockwise);

            int tileX = mViewRect.Left;
            int tileY = mViewRect.Top;

            foreach (Texture2D texture in mTextures)
            {
                if (tileX + mTileWidth > mViewRect.Width)
                {
                    tileX = mViewRect.Left;
                    tileY += mTileHeight;
                }
                mSpriteBatch.Draw(texture, new Rectangle(tileX, tileY, mTileWidth, mTileHeight), Color.White);
                tileX += mTileWidth;
            }

            mSpriteBatch.End();

            // restore graphics state
            GraphicsDevice.BlendState = BlendState.Opaque;
            GraphicsDevice.DepthStencilState = DepthStencilState.Default;

            base.Draw(gameTime);
        }
    }
}
